package com.hcloud.libupload.http

import com.google.gson.GsonBuilder
import com.hcloud.libupload.comom.UploadLib
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class HttpClient {

    companion object {
        @Volatile
        private var instance: HttpClient? = null
        fun instance() = instance ?: synchronized(this) {
            instance ?: HttpClient().also { instance = it }
        }
    }

    val service by lazy {
        getService(UploadApi::class.java, UploadLib.instance().uploadConfig.upNode)
    }

    val fastService by lazy {
        getService(UploadApi::class.java, UploadLib.instance().uploadConfig.mainNode)
    }


    private val client by lazy {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(5, TimeUnit.MINUTES)
                .connectionPool(ConnectionPool(32, 5, TimeUnit.MINUTES))
                .addInterceptor(UploadHeadInterceptor())
                .addInterceptor(httpLoggingInterceptor)
                .build()
    }


    private fun <S> getService(serviceClass: Class<S>, baseUrl: String): S {

        val json =
                GsonBuilder().setLenient().registerTypeAdapterFactory(StringAdapterFactory()).create()

        return Retrofit.Builder()
                .client(client)
                .baseUrl(baseUrl)
                .addConverterFactory(NullOnEmptyConverterFactory())
                .addConverterFactory(GsonConverterFactory.create(json))
                .build()
                .create(serviceClass)
    }

}